<template>
  <div class="container" v-if="LoginPageStore.isShowLoginPage">
    <div class="mask" @click="closeFn"></div>
    <div class="box">
      <div class="close" @click="closeFn">
        <img src="../../../public/images/close.png" alt="" />
      </div>

      <div class="top">
        <span :class="{ active: loginType }" @click="loginType = true">
          手机号码登录
        </span>

        <span :class="{ active: !loginType }" @click="loginType = false">
          微信扫码登录
        </span>
      </div>
      <div class="bottom">
        <div class="phone" v-show="loginType">
          <div>
            <input
              type="text"
              placeholder="请输入手机号"
              v-model.number="phone"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              maxlength="11"
            />
          </div>
          <div ref="verify">
            <slide-verify
              ref="block"
              :imgs="imgs"
              slider-text="向右滑动"
              :accuracy="3"
              :w="370"
              @again="onAgain"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
            ></slide-verify>
          </div>
          <div>
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model.number="code"
              oninput="value=value.replace(/[^0-9.]/g,'')"
              @keyup.enter="loginBtn"
            />
            <div class="code" v-show="showTime" @click="getCode">
              获取验证码
            </div>
            <div class="code time" v-show="!showTime">{{ dTime }}</div>
          </div>
          <div class="loginButton" @click="loginBtn">登录</div>
        </div>
        <div class="weChat" v-show="!loginType">
          <WxLogin
            :appid="wxCodeData.appid"
            :scope="wxCodeData.scope"
            :theme="wxCodeData.theme"
            :redirect_uri="wxCodeData.redirect_uri"
            :href="wxCodeData.href"
            :state="wxCodeData.state"
          ></WxLogin>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useLoginPage } from '../../store/loginPage'
import { ref, inject } from 'vue'
import SlideVerify, { SlideVerifyInstance } from 'vue3-slide-verify'
import 'vue3-slide-verify/dist/style.css'
import WxLogin from 'vue-wxlogin'
import { useRoute, useRouter } from 'vue-router'
import toast from '../toast'
import { ApiSendSMS, ApiPhoneRegin, ApiWechatUsersBinding } from './api'

import img0 from '../../../public/images/integral-01.9386d4bf.png'
import img1 from '../../../public/images/integral-02.150d92a1.png'
import img2 from '../../../public/images/integral-03.9870f3f1.png'
import img3 from '../../../public/images/integral-04.afadcbdf.png'
import { table } from 'console'

const { loginType, key, userInfos } = inject('data') as {
  loginType: any
  key: any
  userInfos: any
}

const LoginPageStore = useLoginPage()
const route = useRoute()
const router = useRouter()
const verify = ref()

const phone = ref<string>('')
const code = ref<string>('')

const dTime = ref<number>(5)
const showTime = ref<boolean>(true)

const imgs = [img0, img1, img2, img3]
const msg = ref('')
const block = ref<SlideVerifyInstance>()

const onAgain = () => {
  msg.value = '检测到非人为操作的哦！ try again'
  // 刷新
  block.value?.refresh()
}

const onSuccess = (times: number) => {
  verify.value.children[0].childNodes[1].style.display = 'none'
  verify.value.children[0].childNodes[3].style.display = 'none'
  msg.value = `success`
}

const onFail = () => {
  msg.value = '请在试一次'
}

const onRefresh = () => {
  msg.value = '点击了刷新小图标'
}

// 微信二维码参数
const wxCodeData = {
  appid: 'wx67cfaf9e3ad31a0d',
  scope: 'snsapi_login',
  theme: 'white',
  redirect_uri: 'https://sc.wolfcode.cn/cms/wechatUsers/shop/PC',
  state: encodeURIComponent(
    window.btoa(`http://127.0.0.1:${window.location.port}${route.path}`),
  ),
  href:
    'data:text/css;base64,LmltcG93ZXJCb3h7DQogICAgbWFyZ2luLXRvcDogMTBweDsNCn0NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogICAgZGlzcGxheTogbm9uZTsNCn0=',
}

// 验证码倒计时
let time: any
const codeTime = () => {
  showTime.value = false
  time = setInterval(() => {
    dTime.value = dTime.value - 1
    if (dTime.value < 0) {
      clearInterval(time)
      showTime.value = true
      dTime.value = 5
    }
  }, 1000)
}

// 检验输入值
const check = () => {
  // 判断输入的手机号是否合法
  if (!/^(?:(?:\+|00)86)?1\d{10}$/.test(phone.value!))
    return toast({ str: '手机号输入不合法!', type: 'warn' })
  if (msg.value !== 'success')
    return toast({ str: '请滑动验证!', type: 'warn' })
}

// 获取验证码
const getCode = () => {
  check()
  ApiSendSMS({ phone: phone.value }).then((res) => {
    if (res.code === 0) {
      codeTime()
      toast({ str: res.message, type: 'success' })
    } else {
      toast({ str: res.message, type: 'warn' })
    }
  })
}

// 登录按钮
const loginBtn = () => {
  check()
  if (code.value === '') return toast({ str: '请填写验证码！', type: 'warn' })
  if (route.query.code) {
    // 绑定手机号
    ApiWechatUsersBinding({
      phone: phone.value,
      verifyCode: code.value,
      uuid: userInfos.uuid,
    }).then((res) => {
      if (res.code === 0) {
        localStorage.setItem('x-auth-token', res['x-auth-token']!)
        router.push('/home')
        setTimeout(() => {
          key.value += 1
        }, 500)

        toast({ str: res.message, type: 'success' })
        closeFn()
      }
    })
  } else {
    // 注册账号
    ApiPhoneRegin({ verifyCode: code.value, phone: phone.value }).then(
      (res) => {
        if (res.code === 0) {
          localStorage.setItem('x-auth-token', res['x-auth-token'])
          toast({ str: res.message, type: 'success' })
          key.value += 1
          closeFn()
        } else {
          toast({ str: res.message, type: 'warn' })
        }
      },
    )
  }
}

// 登录界面关闭
const closeFn = () => {
  LoginPageStore.changeShowLoginPage(false)
  msg.value = ''
  phone.value = ''
  code.value = ''
}
</script>

<style lang="less" scoped>
.container {
  .mask {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
  }
  .box {
    width: 555px;
    height: 423px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-image: url('../../../public/images/login-box-bg.png');
    background-size: 100% 100%;
    text-align: center;
    z-index: 999;
    .close {
      width: 22px;
      height: 22px;
      position: absolute;
      top: 15px;
      right: 60px;
    }
    .top {
      padding-top: 40px;
      font-size: 18px;
      .active {
        color: #333;
      }
      span {
        cursor: pointer;
        color: #ccc;

        &:first-child {
          display: inline-block;
          border-right: 1px solid #ccc;
          padding-right: 10px;
          margin-right: 10px;
        }
      }
    }
    .bottom {
      padding-top: 30px;
      .phone {
        text-align: center;
        div {
          &:nth-of-type(1) {
            input {
              box-sizing: border-box;
              width: 370px;
              height: 50px;
              outline: none;
              text-indent: 1em;
            }
          }
          &:nth-of-type(2) {
            width: 370px;
            height: 50px;
            margin: 20px auto 30px;
            position: relative;

            &:hover {
              :deep(.slide-verify) {
                canvas {
                  display: block;
                }
                .slide-verify-refresh-icon {
                  display: block;
                }
              }
            }
            :deep(.slide-verify) {
              position: absolute;
              left: 0;
              top: 0px;
              margin-top: -150px;

              canvas {
                display: none;
              }

              .slide-verify-refresh-icon {
                display: none;
              }
              .slide-verify-slider {
                position: absolute;
                left: 0;
                top: 145px;
              }
            }
          }
          &:nth-of-type(3) {
            width: 370px;
            margin: 0 auto;
            display: flex;
            align-items: center;
            justify-content: space-between;
            input {
              box-sizing: border-box;
              width: 260px;
              height: 50px;
              outline: none;
              text-indent: 1em;
            }
            .code {
              height: 50px;
              width: 90px;
              background-color: #0a328e;
              color: #fff;
              line-height: 50px;
              cursor: pointer;
            }
            .time {
              opacity: 0.5;
              margin: 0;
            }
          }
        }
        .loginButton {
          width: 370px;
          height: 50px;
          background-color: #0a328e;
          margin: 15px auto;
          line-height: 50px;
          color: #fff;
          font-size: 18px;
        }
      }

      .weChat {
        margin-top: -20px;
        .qrcode {
          width: 282px;
          height: 282px;
        }
      }
    }
  }
}
</style>
